<template>
  <div class="marketing-points">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="积分类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="消费积分" value="consume" />
            <el-option label="签到积分" value="signin" />
            <el-option label="推荐积分" value="referral" />
            <el-option label="活动积分" value="activity" />
            <el-option label="系统赠送" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 积分统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.totalPoints }}</h3>
              <p>总积分发放</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.todayPoints }}</h3>
              <p>今日积分</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon users">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.activeUsers }}</h3>
              <p>活跃用户</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon exchange">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.exchangeCount }}</h3>
              <p>兑换次数</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddPoints">批量发放积分</el-button>
      <el-button type="success" @click="handleExchange">积分兑换管理</el-button>
    </div>

    <!-- 积分记录列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="userPhone" label="用户手机" width="120" />
        <el-table-column prop="userName" label="用户姓名" width="100" />
        <el-table-column prop="type" label="积分类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分变动" width="120">
          <template #default="{ row }">
            <span :class="row.points > 0 ? 'points-add' : 'points-minus'">
              {{ row.points > 0 ? '+' : '' }}{{ row.points }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="currentPoints" label="当前积分" width="100" />
        <el-table-column prop="description" label="变动说明" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewUser(row)">
              用户详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 批量发放积分对话框 -->
    <el-dialog v-model="pointsDialogVisible" title="批量发放积分" width="600px">
      <el-form ref="pointsFormRef" :model="pointsForm" :rules="pointsRules" label-width="100px">
        <el-form-item label="发放对象" prop="targetType">
          <el-radio-group v-model="pointsForm.targetType">
            <el-radio label="all">全部用户</el-radio>
            <el-radio label="vip">VIP用户</el-radio>
            <el-radio label="new">新用户</el-radio>
            <el-radio label="active">活跃用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input-number v-model="pointsForm.points" :min="1" :max="10000" />
        </el-form-item>
        <el-form-item label="积分类型" prop="type">
          <el-select v-model="pointsForm.type" style="width: 100%;">
            <el-option label="活动积分" value="activity" />
            <el-option label="系统赠送" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="发放说明" prop="description">
          <el-input v-model="pointsForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pointsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePointsSubmit" :loading="pointsLoading">
          确认发放
        </el-button>
      </template>
    </el-dialog>

    <!-- 积分兑换管理对话框 -->
    <el-dialog v-model="exchangeDialogVisible" title="积分兑换管理" width="800px">
      <div class="exchange-toolbar">
        <el-button type="primary" size="small" @click="handleAddExchangeItem">
          新增兑换商品
        </el-button>
      </div>
      <el-table :data="exchangeData" border>
        <el-table-column prop="name" label="商品名称" width="150" />
        <el-table-column prop="points" label="所需积分" width="100" />
        <el-table-column prop="stock" label="库存数量" width="100" />
        <el-table-column prop="exchangeCount" label="兑换次数" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch v-model="row.status" @change="handleToggleExchangeStatus(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEditExchangeItem(row)">
              编辑
            </el-button>
            <el-popconfirm title="确定删除该商品吗？" @confirm="handleDeleteExchangeItem(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Coin, Calendar, User, Shop } from '@element-plus/icons-vue'
import { getPointsList, getPointsStats, addPoints, getExchangeList, updateExchangeItem, deleteExchangeItem } from '@/api/wash_service'

export default {
  name: 'MarketingPoints',
  components: {
    Coin, Calendar, User, Shop
  },
  setup() {
    const loading = ref(false)
    const pointsLoading = ref(false)
    const pointsDialogVisible = ref(false)
    const exchangeDialogVisible = ref(false)
    const pointsFormRef = ref()

    const searchForm = reactive({
      phone: '',
      type: '',
      dateRange: []
    })

    const stats = reactive({
      totalPoints: 0,
      todayPoints: 0,
      activeUsers: 0,
      exchangeCount: 0
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])
    const exchangeData = ref([])

    const pointsForm = reactive({
      targetType: 'all',
      points: 100,
      type: 'activity',
      description: ''
    })

    const pointsRules = {
      points: [{ required: true, message: '请输入积分数量', trigger: 'blur' }],
      type: [{ required: true, message: '请选择积分类型', trigger: 'change' }],
      description: [{ required: true, message: '请输入发放说明', trigger: 'blur' }]
    }

    const typeMap = {
      consume: { text: '消费积分', color: 'success' },
      signin: { text: '签到积分', color: 'primary' },
      referral: { text: '推荐积分', color: 'warning' },
      activity: { text: '活动积分', color: 'danger' },
      system: { text: '系统赠送', color: 'info' }
    }

    const getTypeText = (type) => typeMap[type]?.text || type
    const getTypeColor = (type) => typeMap[type]?.color || 'default'

    // 加载积分统计数据
    const loadStatsData = async () => {
      try {
        const res = await getPointsStats()
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          Object.assign(stats, {
            totalPoints: data.totalPoints || 0,
            todayPoints: data.todayPoints || 0,
            activeUsers: data.activeUsers || 0,
            exchangeCount: data.exchangeCount || 0
          })
        }
      } catch (error) {
        console.error('获取积分统计失败:', error)
      }
    }

    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getPointsList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
          pagination.total = data.totalElements || data.total || 0
        } else {
          tableData.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取积分记录失败:', error)
        ElMessage.warning('获取积分记录失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    const loadExchangeData = async () => {
      try {
        const res = await getExchangeList()
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          exchangeData.value = data.content || data.records || data || []
        } else {
          exchangeData.value = []
        }
      } catch (error) {
        console.error('获取兑换商品失败:', error)
        exchangeData.value = []
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, { phone: '', type: '', dateRange: [] })
      handleSearch()
    }

    const handleAddPoints = () => {
      pointsDialogVisible.value = true
      Object.assign(pointsForm, {
        targetType: 'all',
        points: 100,
        type: 'activity',
        description: ''
      })
    }

    const handleExchange = () => {
      exchangeDialogVisible.value = true
      loadExchangeData()
    }

    const handleViewUser = (row) => {
      ElMessage.info(`查看用户 ${row.userName} 的详细信息`)
    }

    const handlePointsSubmit = async () => {
      if (!pointsFormRef.value) return
      
      try {
        await pointsFormRef.value.validate()
        pointsLoading.value = true
        
        const res = await addPoints(pointsForm)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('积分发放成功')
          pointsDialogVisible.value = false
          loadTableData()
          loadStatsData()
        }
      } catch (error) {
        console.error('发放积分失败:', error)
        ElMessage.error('发放积分失败')
      } finally {
        pointsLoading.value = false
      }
    }

    const handleAddExchangeItem = () => {
      ElMessage.info('新增兑换商品功能')
    }

    const handleEditExchangeItem = (row) => {
      ElMessage.info(`编辑商品: ${row.name}`)
    }

    const handleDeleteExchangeItem = async (row) => {
      try {
        const res = await deleteExchangeItem(row.id)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('删除成功')
          loadExchangeData()
        }
      } catch (error) {
        console.error('删除兑换商品失败:', error)
        ElMessage.error('删除失败')
      }
    }

    const handleToggleExchangeStatus = async (row) => {
      try {
        const res = await updateExchangeItem(row.id, { status: row.status })
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(`${row.status ? '启用' : '禁用'}成功`)
        } else {
          row.status = !row.status
        }
      } catch (error) {
        console.error('更新兑换商品状态失败:', error)
        ElMessage.error('操作失败')
        row.status = !row.status
      }
    }

    onMounted(() => {
      loadStatsData()
      loadTableData()
    })

    return {
      loading,
      pointsLoading,
      pointsDialogVisible,
      exchangeDialogVisible,
      pointsFormRef,
      searchForm,
      stats,
      pagination,
      tableData,
      exchangeData,
      pointsForm,
      pointsRules,
      getTypeText,
      getTypeColor,
      loadTableData,
      handleSearch,
      handleReset,
      handleAddPoints,
      handleExchange,
      handleViewUser,
      handlePointsSubmit,
      handleAddExchangeItem,
      handleEditExchangeItem,
      handleDeleteExchangeItem,
      handleToggleExchangeStatus
    }
  }
}
</script>

<style scoped>
.marketing-points {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 36px;
  margin-right: 15px;
  color: #909399;
}

.stat-icon.total {
  color: #E6A23C;
}

.stat-icon.today {
  color: #409EFF;
}

.stat-icon.users {
  color: #67C23A;
}

.stat-icon.exchange {
  color: #F56C6C;
}

.stat-details h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-details p {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.points-add {
  color: #67C23A;
  font-weight: bold;
}

.points-minus {
  color: #F56C6C;
  font-weight: bold;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.exchange-toolbar {
  margin-bottom: 10px;
}
</style> 